<template>
  <div v-loading="processFlg || deviceFlg || clampFlg || personnelFlg " element-loading-text="数据加载中...">
    <el-form ref="form" :model="form" label-width="80px">
      <h2 style="width: 100%; text-align: center; margin-bottom: 50px;">产线设备更换</h2>
      <el-form-item>
        <span>产线名称：</span>
        <el-select v-model="form.lineName" placeholder="请选择产线" filterable clearable style="width:200px;margin-right: 5px" label="产线名称" @change="lineNameChange">
          <el-option
            v-for="item in lineList"
            :key="item.id"
            :label="item.realityLineName"
            :value="item.realityLineName"
          ></el-option>
        </el-select>
        <span style="margin-left: 20px">车间：</span>
        <el-select v-model="workshopId" placeholder="请选择车间" filterable clearable style="width:200px;margin-right: 5px" label="车间" disabled>
          <el-option
            v-for="item in workshopList"
            :key="item.id"
            :label="item.workshopName"
            :value="item.id"
            @click.native="workshopChange(item)"
          ></el-option>
        </el-select>
        <span style="margin-left: 20px">产线类型：</span>
        <el-select v-model="form.lineType" placeholder="请选择产线类型" filterable clearable style="width:200px;margin-right: 5px" label="产线类型" disabled>
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.productCategory"
            :value="item.productCategory"
            @click.native="categoryChange(item)"
          ></el-option>
        </el-select>
<!--        <el-button type="primary" style="margin-left: 100px" @click="downloadTemplate">模版下载</el-button>-->
<!--        <el-button type="primary" @click="importExcel">Excel快速导入</el-button>-->
        <el-button type="primary" @click="save">保存</el-button>
        <!--        <el-button type="primary" @click="handleClose">取消</el-button>-->
<!--        <el-button type="button" class="my-cancel-button" @click="handleClose">取消</el-button>-->
      </el-form-item>
    </el-form>
    <el-table :data="tableData" border>
      <el-table-column type="index" label="序号"></el-table-column>
      <el-table-column label="工序名称">
        <template slot-scope="scope">
          <el-select v-model="scope.row.processName" placeholder="请选择" :disabled="isProcessDisabled">
            <el-option v-for="(item, index) in processList" :key="index" :label="item.processName" :value="item.processName"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="设备">
        <template slot-scope="scope">
          <el-select v-model="scope.row.equipment" placeholder="请选择" style="width: 250px" multiple filterable clearable>
            <el-option v-for="(item, index) in deviceList" :key="index" :label="`${item.deviceName} (${item.deviceSn})`" :value="item.deviceSn"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="夹具">
        <template slot-scope="scope">
          <el-select v-model="scope.row.fixture" placeholder="请选择" multiple style="width: 250px" filterable clearable>
            <el-option v-for="(item, index) in clampList" :key="index" :label="`${item.deviceName} (${item.deviceSn})`" :value="item.deviceSn"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="人员">
        <template slot-scope="scope">
          <el-select v-model="scope.row.personnel" placeholder="请选择" multiple style="width: 250px" filterable clearable>
            <el-option v-for="(item, index) in personCredentialList" :key="index" :label="item.jobNo" :value="item.jobNo"></el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getObj } from '@/api/pfoc/factorysettings' //获取当前工厂信息
import { getDevice } from '@/api/hengdong/pfocinterface' //获取设备相关
import { getWorkshopList } from '@/api/pfoc/workshop' //获取全部车间
import { getPersonCredentialList } from '@/api/workorder/personcredentialmanage'
import { getCategory } from '@/api/workorder/hdviewapiitem' //获取品类
import { getPfocProcessList } from '@/api/pfoc/pfocprocess'
import { updateProductLine, getById, updateLineDevice } from '@/api/pfoc/realityproductlinemain'
import { fetchList } from '@/api/pfoc/realityproductlinemain'


export default {
  data() {
    return {
      form: {
        lineName: '',
        workshop: '',
        lineType: ''
      },
      lineId: null,
      isProcessDisabled: true,
      tableData: [],
      workshopList: [],
      workshopId: null, // 存储选中的车间ID
      processList: [],
      categoryList: [],
      category: null,
      deviceList: [],
      clampList: [],
      toolList: [],
      personCredentialList: [],
      organizationId: null,
      organizationName: null,
      processFlg: true,
      deviceFlg: true,
      clampFlg: true,
      personnelFlg: true,
      jobNo: null,
      loading: null, // 用于存储loading实例
      lineList: [] // 新增：存储产线列表
    }
  },
  created() {
    this.fetchLineList()
    //获取当前工厂信息
    this.getFactoryInfo()
    //获取车间集合
    this.getWorkshopListData()
    //获取所有人员数据
    this.getPersonCredentialListData()
    // 获取产线类型数据
    this.getCategoryData()
    // 获取工序名称数据
    this.getProcessListData()
  },
  mounted() {
    this.addDefaultRows()
    this.jobNo = this.$route.query.jobNo
    console.log('jobNo:', this.jobNo)
  },
  methods: {
    addDefaultRows() {
      for (let i = 0; i < 10; i++) {
        this.tableData.push({
          processName: '',
          equipment: [], // 修改为数组类型，支持多选
          fixture: [], // 修改为数组类型
          personnel: [] // 修改为数组类型，支持多选
        })
      }
    },
    getById() {
      // 显示加载提示
      this.loading = this.$loading({
        lock: true,
        text: '正在加载数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const selectedLine = this.lineList.find(item => item.realityLineName === this.form.lineName)
      if (selectedLine) {
        this.lineId = selectedLine.id
        const data = {
          id: selectedLine.id
        }
        getById(data).then(response => {
          if (response.data.code === 0) {
            const resData = response.data.data
            // 回显表单数据
            this.form.lineName = resData.realityLineName
            this.workshopId = resData.workshopId
            this.form.lineType = resData.lineType

            // 回显表格数据
            this.tableData = resData.list.map(item => {
              return {
                processName: item.processName,
                equipment: item.device ? item.device.split(',') : [], // 将设备字段处理为数组
                fixture: item.clamp ? item.clamp.split(',') : [],
                personnel: item.jobNo ? item.jobNo.split(',') : []
              }
            })
          }
        })
      }
      this.loading.close()
    },
    /**获取工厂信息*/
    getFactoryInfo() {
      const factoryId = 1
      getObj(factoryId).then(response => {
        this.organizationId = response.data.data.menuId //组织ID
        this.organizationName = response.data.data.organizationName //组织名称
        //获取工厂设备集合
        this.getFactoryDeviceList()
      })
    },
    /**获取工厂设备集合*/
    getFactoryDeviceList() {
      var obj = {
        position: this.organizationName //设置组织查询条件
      }
      getDevice(obj).then(response => {
        this.deviceList = response.data.data //设备集合
        for (var i = 0; i < this.deviceList.length; i++) {
          if (this.deviceList[i].deviceClass === '20') { //组织下工具夹具筛选
            this.clampList.push(this.deviceList[i]) //夹具集合
            this.toolList.push(this.deviceList[i]) //工具集合
          }
        }
        this.deviceFlg = false
        this.clampFlg = false
      })
    },
    /**获取车间集合*/
    getWorkshopListData() {
      getWorkshopList().then(response => {
        this.workshopList = response.data.data
      })
    },
    /**车间选择*/
    workshopChange(row) {
      this.workshopName = row.workshopName //车间名称
    },
    //获取所有人员数据
    getPersonCredentialListData() {
      getPersonCredentialList().then(response => {
        this.personCredentialList = response.data.data
        this.personnelFlg = false
      })
    },
    // 获取产线类型数据
    async getCategoryData() {
      getCategory().then(response => {
        this.categoryList = response.data.data
      })
    },
    // 获取工序名称数据
    async getProcessListData() {
      getPfocProcessList().then(response => {
        this.processList = response.data.data
        this.processFlg = false
      })
    },

    /**产线类型选择 */
    categoryChange(row) {
      // this.category = row.
      // 这里可以添加选择产线类型后的逻辑
    },
    save() {
      // 验证产线名称、车间、产线类型是否为空
      if (!this.form.lineName) {
        this.$message.error('产线名称不能为空')
        return
      }
      if (!this.workshopId) {
        this.$message.error('车间不能为空')
        return
      }
      if (!this.form.lineType) {
        this.$message.error('产线类型不能为空')
        return
      }

      // 验证列表是否包含一条工序数据
      if (this.tableData.length === 0 || this.tableData.every(row => !row.processName)) {
        this.$message.error('列表必须包含一条工序数据')
        return
      }

      // 验证列表每一行如果有一个填写了就必须把剩余的都填写完成
      for (let i = 0; i < this.tableData.length; i++) {
        const row = this.tableData[i]
        const hasAnyValue = row.processName || row.equipment.length > 0 || row.fixture.length > 0 || row.personnel.length > 0
        if (hasAnyValue) {
          if (!row.processName) {
            this.$message.error(`第 ${i + 1} 行工序名称未填写`)
            return
          }
        }
      }
      const dataToSave = {
        realityLineName: this.form.lineName,
        workshopId: this.workshopId, // 使用选中的车间ID
        workshopName: '',
        jobNo: this.jobNo,
        lineType: this.form.lineType,
        id: this.lineId,
        list: []
      }

      // 根据ID获取车间名称
      const workshop = this.workshopList.find(w => w.id === this.workshopId)
      if (workshop) {
        dataToSave.workshopName = workshop.workshopName
      }

      // 处理 list 数据，剔除空数据行
      this.tableData.forEach((row, index) => {
        const hasData = row.processName || row.equipment.length > 0 || row.fixture.length > 0 || row.personnel.length > 0
        if (hasData) {
          const item = {
            processId: '', // 假设这里没有提供工序ID的获取逻辑，先设为空字符串
            processName: row.processName,
            nodeId: index + 1, // 假设这里没有提供排序的获取逻辑，先设为空字符串
            device: row.equipment.join(','), // 拼接多选设备编码
            deviceNames: '',
            clamp: '',
            clampNames: '',
            workshopSection: '',
            jobNo: ''
          }

          // 根据设备编码获取设备名称
          const devices = row.equipment.map(code => this.deviceList.find(d => d.deviceSn === code))
          item.deviceNames = devices.filter(Boolean).map(d => d.deviceName).join(',')

          // 获取选中工序id
          const process = this.processList.find(d => d.processName === row.processName)
          if (process) {
            item.processId = process.id
            item.workshopSection = process.workshopSection
          }
          // 处理夹具编码和名称
          item.clamp = row.fixture.map(f => {
            const parts = f.match(/\((.*)\)/)
            return parts ? parts[1] : f
          }).join(',')
          // 循环 clamp 去 clampList 匹配 deviceName 并拼接
          const clampNamesArray = []
          row.fixture.forEach((fixture) => {
            const parts = fixture.match(/\((.*)\)/)
            const fixtureSn = parts ? parts[1] : fixture
            const foundClamp = this.clampList.find(c => c.deviceSn === fixtureSn)
            if (foundClamp) {
              clampNamesArray.push(foundClamp.deviceName)
            }
          })
          item.clampNames = clampNamesArray.join(',')
          // 处理人员数据
          item.jobNo = row.personnel.join(',')
          dataToSave.list.push(item)
        }
      })

      updateLineDevice(dataToSave).then(response => {
        if (response.data.code === 0) {
          this.$message.success('保存成功')
          this.handleClose()
        } else {
          this.$message.error('保存失败：' + response.data.message)
        }
      }).catch(error => {
        console.error('保存请求出错', error)
        this.$message.error('保存过程中出现错误，请检查网络或重试')
      })
    },
    handleClose() {
      this.$emit('closeAdd') //关闭新增页面
    },
    fetchLineList() {
      fetchList().then(response => {
        console.log(response.data.data.records)
        this.lineList = response.data.data.records
      })
    },
    lineNameChange() {
      this.getById()
    }
  }
}
</script>

<style scoped>
::v-deep .my-import-button {
  position: relative;
}

::v-deep .my-cancel-button {
  background-color: white;
  color: black;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
</style>
